import { nextTick, onUnmounted, ref } from 'vue';

/**
 * table 纵向滚动条自动滚动
 *
 * @param className table 的类名
 */
export default function useAutoScrollY(className: string) {
  const table = ref<any>(null);
  const tableEle = ref<any>(null);
  const isStop = ref(false);

  function init() {
    nextTick(() => {
      table.value = document.querySelector(`${className}`);
      tableEle.value = document.querySelector(`${className} .ant-table .ant-table-container .ant-table-body`);
      table.value.addEventListener('mouseleave', () => {
        isStop.value = false;
        scrollStart();
      });
      table.value.addEventListener('mouseenter', scrollStop);
    });
  }
  init();
  function scrollStart() {
    if (isStop.value) return;
    if (tableEle.value.scrollTop >= tableEle.value.scrollHeight - tableEle.value.clientHeight) {
      tableEle.value.scrollTop = 0;
    } else {
      tableEle.value.scrollTop += 1;
    }
    requestAnimationFrame(scrollStart);
  }

  function scrollStop() {
    isStop.value = true;
    scrollStart();
  }

  onUnmounted(() => {
    table.value.removeEventListener('mouseleave');
    table.value.removeEventListener('mouseenter');
  });

  return {
    scrollStart,
    scrollStop,
    tableEle
  };
}
